

class CityTable {
  int rowCount;
  int columnCount;
  float[] [] data;
  String[] cityNames;
  String[] columnNames;
  String[] countries;
  
  CityTable( String filename)
  {
    String[] rows = loadStrings(filename);
    
    String[] columns = split(rows[0], ",");
    columnNames = subset(columns, 0);
    scrubQuotes(columnNames);
    columnCount = columnNames.length;
    
    cityNames = new String[rows.length-1];
    data = new float[rows.length-1] [];
    countries = new String[rows.length-1];
    
    for (int i = 1; i < rows.length; i++)
    {
      if (trim(rows[i]).length() == 0)
      {
        continue;//skip empty rows
      }
      if (rows[i].startsWith("#"))
      {
        continue;//skip comment lines
      }
      
      String[] pieces = split(rows[i], ",");
      scrubQuotes(pieces);
      
      cityNames[rowCount] = pieces[0];
      data[rowCount] = parseFloat( subset( pieces, 1, 3));
      countries[rowCount] = pieces[4];
      
      rowCount++;
    }
    data = (float[][]) subset(data, 0, rowCount);
  }  
  
  void scrubQuotes(String[] array) {
    for (int i = 0; i < array.length; i++) {
      if (array[i].length() > 2) {
        // remove quotes at start and end, if present
        if (array[i].startsWith("\"") && array[i].endsWith("\"")) {
          array[i] = array[i].substring(1, array[i].length() - 1);
        }
      }
      // make double quotes into single quotes
      array[i] = array[i].replaceAll("\"\"", "\"");
    }
  }  
  
  int getRowCount() {
    return rowCount;
  }
  
  
  String getCityName(int rowIndex) {
    return cityNames[rowIndex];
  }
  
  
  String[] getCityNames() {
    return cityNames;
  }

  int getCityIndex(String name) {
    for (int i = 0; i < rowCount; i++) {
      if ( (cityNames[i].toLowerCase()).equals(name.toLowerCase())) {
        return i;
      }
    }
    //println("No row named '" + name + "' was found");
    return -1;
  }
  
  float[] getCoords( int index)
  {
    return subset( data[index], 1);
  }
}
